package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"user-item/models/cache"
	"user-item/models/mysql"
	"user-item/pkg"

	"user-item/userrpc/internal/svc"
	"user-item/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录注册一体化
func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Phone).Result()
	if result != in.CaptchaCode {
		return nil, errors.New("图形验证码错误")
	}
	result2, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Phone).Result()
	if result2 != in.SendSmsCode {
		return nil, errors.New("短信验证码错误")
	}

	var user mysql.User

	if err := user.FindUserByPhone(mysql.DB, in.Phone); err != nil {
		user = mysql.User{
			Phone:     in.Phone,
			Password:  pkg.Md5(in.Password),
			HandImage: "https://bpic.588ku.com/element_origin_min_pic/23/07/11/d32dabe266d10da8b21bd640a2e9b611.jpg!r650",
			NicName:   fmt.Sprintf("用户_%d", rand.Intn(10000)),
		}
		if err := user.UserAdd(mysql.DB); err != nil {
			return nil, errors.New("用户注册失败")
		}
	}
	if user.Password != pkg.Md5(in.Password) {
		return nil, errors.New("密码错误")
	}

	cache.Rdb.Del(l.ctx, "captcha"+in.Phone)
	cache.Rdb.Del(l.ctx, "sendSms"+in.Phone)

	return &userrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
